package com.atguigu.tingshu.common.config.thread;

import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

import java.util.concurrent.ArrayBlockingQueue;
import java.util.concurrent.Executors;
import java.util.concurrent.ThreadPoolExecutor;
import java.util.concurrent.TimeUnit;

/**
 * 配置线程池
 * @author Mahone
 */
@Configuration
public class ThreadPoolConfig {

    /**
     * 线程数应有类型决定，其中N指的是CPU核数（逻辑） ：（大多数Java应用程序）IO密集型：2N+1  CPU密集型：N+1
     * 注册线程池对象
     * @return
     */
    @Bean
    public ThreadPoolExecutor threadPoolExecutor(){
        // 1.获取可用CPU核数
        int count = Runtime.getRuntime().availableProcessors();
        ThreadPoolExecutor threadPoolExecutor = new ThreadPoolExecutor(
                count * 2,
                count * 2,
                0,
                TimeUnit.SECONDS,
                new ArrayBlockingQueue<>(3),
                Executors.defaultThreadFactory(),
                (r, e) -> {
                    // 自定义拒绝策略 r:被拒绝任务对象  e:线程池对象
                    try {
                        Thread.sleep(1000);
                    } catch (InterruptedException ex) {
                        throw new RuntimeException(ex);
                    }
                    // 将任务再次提交给线程池尝试执行
                    e.submit(r);
                }
        );
        // 2.实例化线程同时将核心线程创建 默认：第一个任务提交核心线程才创建
        threadPoolExecutor.prestartCoreThread();
        return threadPoolExecutor;
    }

}
